// Copyright (C) 2023 即时通讯网(52im.net) & Jack Jiang.
// The RainbowChat Project. All rights reserved.
// 
// 【本产品为著作权产品，合法授权后请放心使用，禁止外传！】
// 【本次授权给：<北京小羊驼科技有限公司>，授权编号：<NT231212144350>，代码指纹：<A.702363430.550>，技术对接人微信：<ID: wxid_wbyootvkdcgj22>】
// 【授权寄送：<收件：苏先生、地址：北京市大兴区北京密码西区6号楼1单元301、电话：18613885610、邮箱：bd@huiyuanxiang-inc.com>】
// 
// 【本系列产品在国家版权局的著作权登记信息如下】：
// 1）国家版权局登记名(简称)和权证号：RainbowChat    （证书号：软著登字第1220494号、登记号：2016SR041877）
// 2）国家版权局登记名(简称)和权证号：RainbowChat-Web（证书号：软著登字第3743440号、登记号：2019SR0322683）
// 3）国家版权局登记名(简称)和权证号：RainbowAV      （证书号：软著登字第2262004号、登记号：2017SR676720）
// 4）国家版权局登记名(简称)和权证号：MobileIMSDK-Web（证书号：软著登字第2262073号、登记号：2017SR676789）
// 5）国家版权局登记名(简称)和权证号：MobileIMSDK    （证书号：软著登字第1220581号、登记号：2016SR041964）
// * 著作权所有人：江顺/苏州网际时代信息科技有限公司
// 
// 【违法或违规使用投诉和举报方式】：
// 联系邮件：jack.jiang@52im.net
// 联系微信：hellojackjiang
// 联系QQ号：413980957
// 授权说明：http://www.52im.net/thread-1115-1-1.html
// 官方社区：http://www.52im.net
package com.x52im.rbchat.logic.chat_root.sendlocation;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.eva.android.widget.DataLoadableActivity;
import com.eva.android.widget.WidgetUtils;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.dto.DataFromServer;
import com.x52im.rbchat.R;
import com.x52im.rbchat.logic.chat_root.model.LocationMeta;
import com.x52im.rbchat.logic.chat_root.sendlocation.impl.GetLocationPOIEntity;
import com.x52im.rbchat.logic.chat_root.sendlocation.impl.GetMyselfLocationWrapper;
import com.x52im.rbchat.logic.chat_root.sendlocation.utils.LocationUtils;
import com.x52im.rbchat.logic.chat_root.sendlocation.utils.MapNaviUtils;
import com.x52im.rbchat.permission2.PermissionManager;
import com.x52im.rbchat.utils.IntentFactory;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 查看地理位置。支持打开第3方地图导航功能。
 *
 * @author JackJiang
 * @since 6.0
 */
public class ViewLocationActivity extends DataLoadableActivity {

    private final String TAG = SearchLocationActivity.class.getSimpleName();

    /** 第3方导航选择选项弹出框类 */
    private MapNaviUtils.ThridpartMapNavigationChoicePopWindow menuWindowFor3rdNavi = null;

    /** 获取我自已的当前位置定位的wrapper包装类 */
    private GetMyselfLocationWrapper getMyselfLocationWrapper;

    /** 按钮：更多。。。 */
    private Button btnSeeMore = null;

    /** 地图主视图 */
    private MapView mMapView;
    private TextView mIv_destLocationTitle;
    private TextView mIv_destLocationContent;
    private ImageView mIv_gotoNavi;

    /** 回到"我自已的当前位置"组件 */
    private ImageView mIvBackMySelfLocation;

    private AMap mAMap;
//    /** "我自已的当前位置"地图标记 */
//    private Marker mMyselfLocationMarker;
    /** 默认地图缩放级别 */
    private float           zoom         = 14;

    /** "目的地位置"地图标记 */
    private Marker mDestinationLocationMarker;
    /** Intent中传过来的"目的地位置"数据 */
    private LocationMeta destLocationMetaFromIntent;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        initPermission();
        initDatas();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();

        getMyselfLocationWrapper.stopLocation();
        mMapView.onDestroy();
        getMyselfLocationWrapper.onDestroy();
    }

    /**
     * 从Intent中读取传递过来的数据。
     */
    @Override
    protected void initDataFromIntent()
    {
        //解析从intent中传过来的数据
        ArrayList intentDatas = IntentFactory.parseViewLocationActivityIntent(getIntent());
        destLocationMetaFromIntent = (LocationMeta) intentDatas.get(0);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        //设定自定义标题栏（设定此值即意味着开启自定义标题栏的使用，必须要在setContentView前设定）
        customeTitleBarResId = R.id.chatting_view_location_activity_titleBar;
        setContentView(R.layout.chatting_view_location_activity);

        this.setTitle("位置信息");

        // 自定义标题组件配置
        this.btnSeeMore = this.getCustomeTitleBar().getRightGeneralButton();
        this.btnSeeMore.setVisibility(View.VISIBLE);
        this.btnSeeMore.setText("");
        this.btnSeeMore.setBackgroundResource(R.drawable.common_title_btn_more);

        mMapView = findViewById(R.id.chatting_view_location_activity_map);
        mIv_destLocationTitle = findViewById(R.id.chatting_view_location_activity_tv_title);
        mIv_destLocationContent = findViewById(R.id.chatting_view_location_activity_tv_message);
        mIvBackMySelfLocation = findViewById(R.id.chatting_view_location_activity_iv_back_myself_location);
        mIv_gotoNavi = findViewById(R.id.chatting_view_location_activity_ivNavigationTo);

        getMyselfLocationWrapper = new GetMyselfLocationWrapper(this,false) {
            @Override
            protected void whenLocationSucess() {
                doWhenMyselfLocationSucess(false);
            }
            @Override
            protected void showHint(String hint) {
                Log.d(TAG, "【查看位置】"+hint);
            }
        };

        // 此方法必须重写
        mMapView.onCreate(savedInstanceState);
        mAMap = mMapView.getMap();

        //是否显示地图中放大缩小按钮
        mAMap.getUiSettings().setZoomControlsEnabled(false);
        // 是否显示默认的定位按钮
        mAMap.getUiSettings().setMyLocationButtonEnabled(false);
        //是否显示缩放级别
        mAMap.getUiSettings().setScaleControlsEnabled(true);
        // 是否可触发定位并显示定位层
        mAMap.setMyLocationEnabled(false);
    }

    @Override
    protected void initListeners() {

        // 监测地图画面的移动事件监听器
        mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition)
            {
//                if (null != getMyselfLocationWrapper.getCurrentLocation() && null != cameraPosition)
                if(null != cameraPosition)
                {
                    mIvBackMySelfLocation.setImageResource(R.drawable.chatting_location_gps_black);
                    zoom = cameraPosition.zoom;
                }
            }

            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }
        });

        mIvBackMySelfLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIvBackMySelfLocation.setImageResource(R.drawable.chatting_location_gps_red);

//                if (null == getMyselfLocationWrapper.getCurrentLocation()) {
//                    getMyselfLocationWrapper.startLocation();
//                } else {
//                    doWhenMyselfLocationSucess(true);
//                    WidgetUtils.showToast(ViewLocationActivity.this
//                            , "已成功回到\"我\"的当前位置！", WidgetUtils.ToastType.OK);
//                }


                if(destLocationMetaFromIntent != null)
                    moveMapCamera(destLocationMetaFromIntent.getLatitude(), destLocationMetaFromIntent.getLongitude());
            }
        });

        View.OnClickListener clickTo3rdNaviListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show3rdNavigationMap();
            }
        };
        btnSeeMore.setOnClickListener(clickTo3rdNaviListener);
        mIv_gotoNavi.setOnClickListener(clickTo3rdNaviListener);
    }

    private void initPermission()
    {
        // 开始动态权限申请（用于targetSDKVersion>=23，即Android6.0及以上系统时）
        PermissionManager.requestPermission_LOCATION(this
                // 权限获取成功或已经取得此权限时
                , new Observer() {
                    @Override
                    public void update(Observable o, Object arg) {

                        //** 权限正常获取，走正常的代码逻辑。。。

                        // 开始定位
                        getMyselfLocationWrapper.startLocation();
                    }
                }
                // 用户拒绝或权限获取失败时
                , new Observer(){
                    @Override
                    public void update(Observable o, Object permissionNamesObj) {

                        final List<String> permissionNames = (List<String>)permissionNamesObj;
                        String message = MessageFormat.format($$(R.string.rb_permission_setting_content)
                                , com.eva.android.ToolKits.getAppName(ViewLocationActivity.this), permissionNames);

                        // 显示提示信息
//                        showHintContent(message);
                        Log.w(TAG, "【查看位置】"+message);
                        WidgetUtils.showToast(ViewLocationActivity.this, message, WidgetUtils.ToastType.WARN);
                    }
                });
    }

    private void initDatas()
    {
        if(destLocationMetaFromIntent != null)
        {
            double longitude = destLocationMetaFromIntent.getLongitude();
            double latitude = destLocationMetaFromIntent.getLatitude();

            String title = CommonUtils.isStringEmpty(destLocationMetaFromIntent.getLocationTitle(), true)
                    ?$$(R.string.general_location_desc): destLocationMetaFromIntent.getLocationTitle();
            String content = CommonUtils.isStringEmpty(destLocationMetaFromIntent.getLocationContent(), true)
                    ?("经度:"+ longitude+" 纬度:"+ latitude): destLocationMetaFromIntent.getLocationContent();

            this.mIv_destLocationTitle.setText(title);
            this.mIv_destLocationContent.setText(content);
            this.refleshDestinationLocationMark(latitude, longitude);
        }
    }

    /**
     * 当"我自已的位置"定位成功后要做的事情。
     */
    private void doWhenMyselfLocationSucess(boolean moveCarmera)
    {
        AMapLocation location = getMyselfLocationWrapper.getCurrentLocation();

        Log.i(TAG, "【查看位置】已成功定位到我的位置："+location);

//        if(moveCarmera)
//            moveMapCamera(location.getLatitude(), location.getLongitude());
//        refleshDefaultLocationMark(location.getLatitude(), location.getLongitude());
    }

    /**
     * 把地图画面移动到定位地点(使用moveCamera方法没有动画效果)
     *
     * @param latitude
     * @param longitude
     */
    private void moveMapCamera(double latitude, double longitude)
    {
        if (null != mAMap) {
            mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), zoom));
        }
    }

//    /**
//     * 刷新默认位置标识（默认位置即首次进入本界面时定位得到的那个位置）。
//     *
//     * @param latitude
//     * @param longitude
//     */
//    private void refleshDefaultLocationMark(double latitude, double longitude)
//    {
//        if (mMyselfLocationMarker == null) {
//            mMyselfLocationMarker = mAMap.addMarker(new MarkerOptions()
//                    .position(new LatLng(latitude, longitude))
//                    .anchor(0.5f, 0.6f)// anchor(..)方法用于设定显示坐标的偏移，0.5f表示居中，详见：http://a.amap.com/lbs/static/unzip/Android_Map_Doc/3D/com/amap/api/maps/model/MarkerOptions.html#anchor-float-float-
//                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
//                            .decodeResource(getResources(), R.drawable.chatting_location_current_flag_icon)))
//                    .draggable(true)
//            );
//        }
//        mMyselfLocationMarker.setPosition(new LatLng(latitude, longitude));
////        mAMap.invalidate();
//    }

    /**
     * 刷新目的地位置标识。
     *
     * @param latitude
     * @param longitude
     */
    private void refleshDestinationLocationMark(double latitude, double longitude)
    {
        if (mDestinationLocationMarker == null) {
            mDestinationLocationMarker = mAMap.addMarker(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    .anchor(0.5f, 1.0f)// anchor(..)方法用于设定显示坐标的偏移，0.5f表示居中，详见：http://a.amap.com/lbs/static/unzip/Android_Map_Doc/3D/com/amap/api/maps/model/MarkerOptions.html#anchor-float-float-
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.drawable.chatting_location_current_pin_icon)))
                    .draggable(true)
                    .zIndex(999)
            );
        }
        mDestinationLocationMarker.setPosition(new LatLng(latitude, longitude));
        moveMapCamera(latitude, longitude);
    }

    private void show3rdNavigationMap()
    {
        // 实例化menuWindowFor3rdNavi
        if(menuWindowFor3rdNavi == null)
        {
            // 为选项弹出窗口实现监听类
            View.OnClickListener itemsOnClickForSendPic = new View.OnClickListener(){
                public void onClick(View v)
                {
                    menuWindowFor3rdNavi.dismiss();

                    try{
                        AMapLocation fromLocation = getMyselfLocationWrapper.getCurrentLocation();
                        GetLocationPOIEntity fromPOI = LocationUtils.changeToPoiItem(fromLocation);

                        // 源地址（我本地的地址）
                        double fromLatitude = 0;
                        double fromLongtitude = 0;
                        String fromTitle = null;
                        if(fromLocation != null) {
                            fromLatitude = fromLocation.getLatitude();
                            fromLongtitude = fromLocation.getLongitude();
                            fromTitle = (fromPOI != null?fromPOI.getTitle():null);
                        }

                        // 目的地地址
                        double toLatitude = 0;
                        double toLongtitude = 0;
                        String toTitle = null;
                        if(destLocationMetaFromIntent != null){
                            toLatitude = destLocationMetaFromIntent.getLatitude();
                            toLongtitude = destLocationMetaFromIntent.getLongitude();
                            toTitle = destLocationMetaFromIntent.getLocationTitle();
                        }

                        Log.d(TAG, "【查看位置】正在调用导航，from：[经"+fromLongtitude+", 纬"+fromLatitude
                                +"]，to：[经"+toLongtitude+",纬"+toLatitude+"]");

                        // 打开第3方导航
                        switch (v.getId())
                        {
                            case R.id.chatting_location_goto_3rdnavi_choice_dialog_btn_tencent:
                            {
                                Log.d(TAG, "【查看位置】正在进入腾讯地图进行导航，腾讯地图已安装？"
                                        +MapNaviUtils.isTencentMapInstalled(ViewLocationActivity.this));
                                MapNaviUtils.openTencentMap(ViewLocationActivity.this
                                        , fromLatitude, fromLongtitude, fromTitle, toLatitude, toLongtitude, toTitle);
                                break;
                            }
                            case R.id.chatting_location_goto_3rdnavi_dialog_btn_pick_baidu:
                            {
                                Log.d(TAG, "【查看位置】正在进入百度地图进行导航，百度地图已安装？"
                                        +MapNaviUtils.isBaiduMapInstalled(ViewLocationActivity.this));
                                MapNaviUtils.openBaiDuNavi(ViewLocationActivity.this
                                        , fromLatitude, fromLongtitude, fromTitle, toLatitude, toLongtitude, toTitle);
                                break;
                            }
                            case R.id.chatting_location_goto_3rdnavi_dialog_btn_pick_gaode:
                            {
                                Log.d(TAG, "【查看位置】正在进入高德地图进行导航，高德地图已安装？"
                                        +MapNaviUtils.isGdMapInstalled(ViewLocationActivity.this));
                                MapNaviUtils.openGaoDeNavi(ViewLocationActivity.this
                                        , fromLatitude, fromLongtitude, fromTitle, toLatitude, toLongtitude, toTitle);
                                break;
                            }
                            default:
                                break;
                        }
                    }
                    catch (Exception e){
                        Log.w(TAG, e);
                        WidgetUtils.showWithDialog(ViewLocationActivity.this
                                , $$(R.string.general_prompt), $$(R.string.get_location_goto_3rd_fail));
                    }
                }
            };
            menuWindowFor3rdNavi = new MapNaviUtils.ThridpartMapNavigationChoicePopWindow(ViewLocationActivity.this, itemsOnClickForSendPic);
        }
        //显示窗口
        menuWindowFor3rdNavi.showAtLocation(this.mIv_gotoNavi
                , Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
    }

    @Override
    protected DataFromServer queryData(String... params) {
        return null;
    }

    @Override
    protected void refreshToView(Object dateToView) {

    }
}
